package yxgf.oem.oemquotemgt.plugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.field.events.AfterF7SelectEvent;
import kd.bos.form.field.events.AfterF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import yxgf.oem.oemquotemgt.commons.constant.MarketBillConstants;
import yxgf.oem.oemquotemgt.commons.dto.PriceDto;
import yxgf.oem.oemquotemgt.commons.enums.BillMsgEnum;
import yxgf.oem.oemquotemgt.commons.enums.StockTypeEnum;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description： 营销配方插件
 * @version: v1.0
 * @author: Junit
 * @date: 2025/5/12
 */
public class MarketBillFormPlugIn extends AbstractFormPlugin implements AfterF7SelectListener {

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        setDefStockType();
    }


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
    }


    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();
        boolean formulaListener;
        switch (fieldKey) {
            case MarketBillConstants.MAT_FORMULA_CODE:
                formulaListener = true;
                DynamicObject formulaObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                buildMaterPriceDetail(formulaObj.getString("number"), formulaListener);
                break;
            case MarketBillConstants.MAT_DETAIL_CODE:
                formulaListener = false;
                DynamicObject detailObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                buildMaterPriceDetail(detailObj.getString("number"), formulaListener);
                break;
            case MarketBillConstants.BUS_DATE:
                setDefStockType();
                break;
            default: break;
        }
    }

    /**
     * 构建原料明细
     *
     * @param materialCode
     * @param formulaListener
     */
    private void buildMaterPriceDetail(String materialCode, boolean formulaListener) {
        DynamicObjectCollection collection = getModel().getEntryEntity(MarketBillConstants.MAT_PRICE_DETAIL);
        Object detailObj = collection.get(0).get(MarketBillConstants.MAT_DETAIL_CODE);
        int row = 0;
        if (formulaListener) {
            if (detailObj != null) {
                row = this.getModel().createNewEntryRow(MarketBillConstants.MAT_PRICE_DETAIL);
            }
            addRowData(row, collection, materialCode, formulaListener);
        } else {
            addRowData(row, collection, materialCode, formulaListener);
        }
    }

    /**
     * 设置价格行
     *
     * @param row
     * @param dynamicObjects
     * @param materialCode
     * @param formulaListener
     */
    private void addRowData(int row, DynamicObjectCollection dynamicObjects, String materialCode, boolean formulaListener) {
        QFilter qfilter = new QFilter("number", QCP.equals, materialCode);
        DynamicObject mts = QueryServiceHelper.queryOne("bd_material", "id", qfilter.toArray());

        if (!formulaListener) {
            if (dynamicObjects.size() >= 1) {
                setPriceInfo(dynamicObjects.size() - 1, materialCode);
            }
        } else {
            getModel().setValue(MarketBillConstants.MAT_DETAIL_CODE, mts.get("id"), row);
            setPriceInfo(row, materialCode);
        }
        getModel().updateEntryCache(dynamicObjects);
    }

    /**
     * 价格处理
     * @param index
     * @param materialCode
     */
    private void setPriceInfo(int index, String materialCode) {
        DynamicObject orgObj = (DynamicObject) this.getModel().getValue("yxgf_orgfield");
        Date busDat = (Date) this.getModel().getValue("yxgf_business_date");
        if (orgObj != null) {
            String masterId = (String) orgObj.get("number");
            String stockType = (String) getModel().getValue("yxgf_kcjlx");

            CustomApiResult<PriceDto> apiResult = DispatchServiceHelper.invokeService("yxgf.oem.oemquotemgt.mservice.factory", "llj-quotemgt",
                    "IPriceService", "getPriceList", masterId, materialCode,stockType,"");
            PriceDto res = apiResult.getData();
            getModel().setValue("yxgf_mark_price", res.getForPrice(), index);
            getModel().setValue("yxgf_stock_price", res.getStockPrice(), index);
            getModel().setValue("yxgf_comp_price", res.getCompPrice(), index);
            getModel().setValue("yxgf_cwyljj_text", res.getFinancePrice(), index);
        } else {
            this.getView().showMessage(BillMsgEnum.ERROR_MARKET_NOT_ORG.getName());
        }
    }

    @Override
    public void afterF7Select(AfterF7SelectEvent afterF7SelectEvent) {
    }


    private void setDefStockType(){
        Date busDat = (Date) this.getModel().getValue(MarketBillConstants.BUS_DATE);
        SimpleDateFormat dayFormat = new SimpleDateFormat("d");
        if (Integer.parseInt(dayFormat.format(busDat)) > MarketBillConstants.DAYS) {
            getModel().setValue(MarketBillConstants.STOCK_TYPE, StockTypeEnum.MARKET_SEC_HALF_MONTH.getCode());
        }else {
            getModel().setValue(MarketBillConstants.STOCK_TYPE, StockTypeEnum.MARKET_FIRST_HALF_MONTH.getCode());
        }
    }
}
